# -*- coding:utf-8 -*-
from fastapi import FastAPI, Request
from config.app import get_config
import logging
import time

def register_logger(app: FastAPI) -> None:
    """
    系统日志设置
    """
    settings = get_config()

    today = time.strftime("%Y%m%d")

    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)
    formatter = logging.Formatter("%(asctime)s - %(module)s - %(funcName)s - line:%(lineno)d - %(levelname)s - %(message)s")
    cf = logging.FileHandler(filename=settings.ROOT_PATH+'/runtime/log/server_'+today+'.log', mode="a", encoding="utf8")
    cf.setFormatter(formatter)
    logger.addHandler(cf) #日志输出至文件

    @app.middleware("http")
    async def log_requests(req:Request, call_next):
        """
        日志输出中间件
        :param req:
        :param call_next:
        :return:
        """
        start_time = time.time()
        resp = await call_next(req)
        process_time = (time.time() - start_time) * 1000
        formatted_process_time = '{0:.2f}'.format(process_time)

        now = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
        if process_time>100:
            # 慢查询记录日志
            log = f"{req.client.host} - - [{now}] - {req.method} - {resp.status_code} - {req.url.path} - [{req.headers.get('User-Agent')}] - {formatted_process_time}ms"
            with open(settings.ROOT_PATH+"/runtime/log/slow_"+today+".log","a", encoding='utf8') as f:
                f.write(log+"\n")

        log = f"{req.client.host} - - [{now}] - {req.method} - {resp.status_code} - {req.url.path} - [{req.headers.get('User-Agent')}] - {formatted_process_time}ms"
        with open(settings.ROOT_PATH+"/runtime/log/access_"+today+".log","a", encoding='utf8') as f:
            f.write(log+"\n")
        resp.headers["time"] = now

        return resp